﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using MockBusiness;
using MockCommon;
using MockDataTransferObject;
using System.Drawing;
using System.Web.UI;
using System.Globalization;

namespace Presentation
{
    public partial class AddTimesheet : System.Web.UI.Page
    {
        private MessageBusiness _messageBusiness;
        private TimesheetStatusBusiness _timesheetStatusBusiness;
        private TimesheetBusiness _timesheetBusiness;
        private ContractBusiness _contractBusiness;
        private Label _warningLabel;
        private Label _errorLabel;
        private Label _successLabel;
        private GridView _timesheetGridView;
        private Button _addButton;

        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                _messageBusiness = MessageBusiness.RetrieveInstance();
                _timesheetStatusBusiness = TimesheetStatusBusiness.RetrieveInstance();
                _timesheetBusiness = TimesheetBusiness.RetrieveInstance();
                _contractBusiness = ContractBusiness.RetrieveInstance();
                _warningLabel = (Label)Master.FindControl("WarningLabel");
                _errorLabel = (Label)Master.FindControl("ErrorLabel");
                _successLabel = (Label)Master.FindControl("SuccessLabel");
                _timesheetGridView = (GridView)AddTimesheetUserControl.FindControl("TimesheetGridView");
                _addButton = (Button)AddTimesheetUserControl.FindControl("AddButton");
                _addButton.Click += new EventHandler(AddButton_Click);
            }
            catch (MockException exception)
            {
                Application["error"] = exception;
                Response.Redirect("Error.aspx");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user"] == null)
            {
                Response.Redirect("LogOn.aspx");
            }
            else
            {
                User user = (User)Session["user"];
                if (user.Role.RoleName != "Contractor")
                {
                    Server.Transfer("NotAuthorized.aspx");
                }
            }
            if (!Page.IsPostBack)
            {
                BindGrid(5);
            }
            else
            {
                _warningLabel.Text = "";
                _errorLabel.Text = "";
                _successLabel.Text = "";
            }
            Format();
        }

        protected void AddButton_Click(object sender, EventArgs e)
        {
            List<MockDataTransferObject.Timesheet> timesheets = new List<MockDataTransferObject.Timesheet>();
            try
            {
                int countRow = 0;
                int countContinue = 0;
                string statusName = "Pending";
                bool isValid = true;
                Control timesheetDateControl = null;
                Control workingTimeControl = null;
                Control titleControl = null;
                Control descriptionControl = null;
                TextBox timesheetDateTextBox = null;
                TextBox workingTimeTextBox = null;
                TextBox titleTextBox = null;
                TextBox descriptionTextBox = null;
                foreach (GridViewRow row in _timesheetGridView.Rows)
                {
                    countRow++;
                    MockDataTransferObject.Timesheet timesheet = new MockDataTransferObject.Timesheet();
                    TimesheetStatus status = new TimesheetStatus();
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        Guid statusId = new Guid();
                        //Get status
                        object statusIdObject = _timesheetStatusBusiness.GetStatusIdByStatusName(statusName);
                        if (statusIdObject != null)
                        {
                            statusId = Guid.Parse(statusIdObject.ToString());
                        }
                        //Get contractor's user
                        User user = new User();
                        if (Session["user"] != null)
                        {
                            user = (User)Session["user"];
                        }
                        //Get contract id of contractor's user
                        object contractIdObject = _contractBusiness.GetContractIdByContractorUserId(user.UserId);
                        Guid contractId = new Guid();
                        if (contractIdObject != null && contractIdObject is Guid)
                        {
                            contractId = Guid.Parse(contractIdObject.ToString());
                        }
                        //Get contract by contractId
                        Contract contract = _contractBusiness.GetById(contractId);
                        //get value from Control
                        timesheetDateControl = row.FindControl("DateTimeTextBox");
                        workingTimeControl = row.FindControl("WorkingTimeTextBox");
                        titleControl = row.FindControl("TitleTextBox");
                        descriptionControl = row.FindControl("DescriptionTextBox");
                        timesheetDateTextBox = new TextBox();
                        workingTimeTextBox = new TextBox();
                        titleTextBox = new TextBox();
                        descriptionTextBox = new TextBox();
                        if (timesheetDateControl != null)
                        {
                            timesheetDateTextBox = (TextBox)timesheetDateControl;
                        }
                        if (workingTimeControl != null)
                        {
                            workingTimeTextBox = (TextBox)workingTimeControl;
                        }
                        if (titleControl != null)
                        {
                            titleTextBox = (TextBox)titleControl;
                        }
                        if (descriptionControl != null)
                        {
                            descriptionTextBox = (TextBox)descriptionControl;
                        }
                        string timesheetDateInput = timesheetDateTextBox.Text;
                        string workingTimeInput = workingTimeTextBox.Text;
                        string titleInput = titleTextBox.Text;
                        string descriptionInput = descriptionTextBox.Text;
                        DateTime timesheetDate = DateTime.Now;
                        bool timesheetDateValid = DateTime.TryParse(timesheetDateInput, out timesheetDate);
                        bool workingEmpty = String.IsNullOrEmpty(workingTimeInput);
                        bool titleEmpty = String.IsNullOrEmpty(titleInput);
                        bool descriptionEmpty = String.IsNullOrEmpty(descriptionInput);
                        if (timesheetDateValid && workingEmpty && titleEmpty && descriptionEmpty)
                        {
                            countContinue++;
                            continue;
                        }
                        else
                        {
                            if (!timesheetDateValid)
                            {
                                timesheetDateTextBox.Attributes["title"] = "Date time is invalid";
                                timesheetDateTextBox.CssClass = "inp-datetime-error";
                                isValid = false;
                            }
                            else if (!CheckDateTimeValid(timesheetDate))
                            {
                                timesheetDateTextBox.Attributes["title"] = "Date time must in range from " + contract.StartDate.ToString("MM/dd/yyyy", CultureInfo.CurrentCulture) + "to " + contract.EndDate.ToString("MM/dd/yyyy", CultureInfo.CurrentCulture);
                                timesheetDateTextBox.CssClass = "inp-datetime-error";
                                isValid = false;
                            }
                            int workingTime = 0;
                            bool workingTimeValid = Int32.TryParse(workingTimeInput, out workingTime);
                            if (!workingTimeValid)
                            {
                                workingTimeTextBox.Attributes["title"] = "Working time is invalid";
                                workingTimeTextBox.CssClass = "inp-form-error";
                                isValid = false;
                            }
                            else if (!TimesheetBusiness.CheckWorkingTimeValid(workingTime))
                            {
                                workingTimeTextBox.Attributes["title"] = "Working time must in range (1-23)";
                                workingTimeTextBox.CssClass = "inp-form-error";
                                isValid = false;
                            }
                            if (titleEmpty)
                            {
                                titleTextBox.Attributes["title"] = "Title is required";
                                titleTextBox.CssClass = "inp-form-error";
                                isValid = false;
                            }
                            if (descriptionEmpty)
                            {
                                descriptionTextBox.Attributes["title"] = "Description is required";
                                descriptionTextBox.CssClass = "inp-form-error";
                                isValid = false;
                            }
                            timesheet.TimesheetId = Guid.NewGuid();
                            timesheet.TimesheetDate = timesheetDate;
                            timesheet.WorkingTime = workingTime;
                            timesheet.Title = titleInput;
                            timesheet.Description = descriptionInput;
                            status.StatusId = statusId;
                            timesheet.Status = status;
                            timesheet.Contract = contract;
                            timesheets.Add(timesheet);
                        }
                    }
                }
                if (countContinue == countRow)
                {
                    _warningLabel.Text = "You have entered no record !";
                }
                else if (isValid)
                {
                    bool insertDone = false;
                    foreach (MockDataTransferObject.Timesheet timesheet in timesheets)
                    {
                        _timesheetBusiness.Insert(timesheet);
                        Notify(timesheet);
                        insertDone = true;
                    }
                    if (insertDone)
                    {
                        _addButton.Enabled = false;
                        Response.Redirect("ListTimesheet.aspx");
                    }
                }
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (ArgumentException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (FormatException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        private void Notify(MockDataTransferObject.Timesheet timesheet)
        {
            User fromUser = Session["user"] as User;
            User toUser = timesheet.Contract.Client.User;
            Message message = new Message();
            string content = @"Dear <b>{0}</b><br/> 
                               Your contractor has sent a timesheet and need you confirm.
                               Timesheet was created by <b>{1}</b>.<br/>
                               Some brief of your timesheet as below:<br/>
                               <div class=""contentMail"">
                               -TimesheetDate: <b>{2}</b>.<br/>
                               -Title: <b>{3}</b>.<br/>
                               -Description: <b>{4}</b>.<br/>
                               -Working time: <b>{5}</b>.<br/>
                               </div><br/>
                               Please confirm it as soon as possibile!<br/><br/>
                               <b>CMS AutoMailer.</b><br/>
                               <b>&</b>
                               <b>Best Regards!</b>";
            message.MessageId = Guid.NewGuid();
            message.From = fromUser;
            message.To = toUser;
            message.Title = String.Format(CultureInfo.CurrentCulture, "<b>{0}</b> has sent new timesheet", fromUser.UserName);
            message.Content = String.Format(CultureInfo.CurrentCulture, content, toUser.UserName, fromUser.UserName, timesheet.TimesheetDate.ToString("dd/MM/yyyy hh:mm:ss", CultureInfo.CurrentCulture), timesheet.Title, timesheet.Description, timesheet.WorkingTime);
            message.IsRead = false;
            message.IsReceive = false;
            message.SendDate = DateTime.Now;
            _messageBusiness.Insert(message);
        }

        private bool CheckDateTimeValid(DateTime dateTime)
        {
            User user = (User)Session["user"];
            object contractIdObject = _contractBusiness.GetContractIdByContractorUserId(user.UserId);
            Guid contractId = new Guid();
            if (contractIdObject != null && contractIdObject is Guid)
            {
                contractId = Guid.Parse(contractIdObject.ToString());
            }
            Contract contract = _contractBusiness.GetById(contractId);
            DateTime startDate = contract.StartDate;
            DateTime endDate = contract.EndDate;
            try
            {
                if (dateTime.CompareTo(startDate) > 0 && dateTime.CompareTo(endDate) < 0)
                {
                    return true;
                }
                return false;
            }
            catch (NullReferenceException)
            {
                return false;
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (FormatException)
            {
                return false;
            }
            catch (MockException)
            {
                return false;
            }
        }

        private void BindGrid(int numberRow)
        {
            List<MockDataTransferObject.Timesheet> items = new List<MockDataTransferObject.Timesheet>();
            DateTime dateNow = DateTime.Now;
            int days;
            for (int i = 0; i < numberRow; i++)
            {
                days = i - numberRow / 2;
                MockDataTransferObject.Timesheet timesheet = new MockDataTransferObject.Timesheet();
                timesheet.TimesheetDate = dateNow.AddDays(days);
                items.Add(timesheet);
                items.Add(timesheet);
            }
            _timesheetGridView.DataSource = items;
            _timesheetGridView.DataBind();
        }

        private void Format()
        {
            try
            {
                Control dateTimeControl = null;
                Control workingTimeControl = null;
                Control titleControl = null;
                Control descriptionControl = null;
                foreach (GridViewRow row in _timesheetGridView.Rows)
                {
                    dateTimeControl = row.FindControl("DateTimeTextBox");
                    workingTimeControl = row.FindControl("WorkingTimeTextBox");
                    titleControl = row.FindControl("TitleTextBox");
                    descriptionControl = row.FindControl("DescriptionTextBox");
                    if (dateTimeControl != null)
                    {
                        TextBox dateTimeTextBox = (TextBox)dateTimeControl;
                        dateTimeTextBox.CssClass = "inp-datetime";
                        dateTimeTextBox.Attributes["title"] = "";
                    }
                    if (workingTimeControl != null)
                    {
                        TextBox workingTimeTextBox = (TextBox)workingTimeControl;
                        workingTimeTextBox.CssClass = "inp-form";
                        workingTimeTextBox.Attributes["title"] = "";
                    }
                    if (titleControl != null)
                    {
                        TextBox titleTextBox = (TextBox)titleControl;
                        titleTextBox.CssClass = "inp-form";
                        titleTextBox.Attributes["title"] = "";
                    }
                    if (descriptionControl != null)
                    {
                        TextBox descriptionTextBox = (TextBox)descriptionControl;
                        descriptionTextBox.CssClass = "inp-form";
                        descriptionTextBox.Attributes["title"] = "";
                    }
                }
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
        }
    }
}